﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.RBAC;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.Menus;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.Menus
{
    /// <summary>
    /// MVC动态菜单
    /// </summary>
    public class GetMenuListCommandHandler : IRequestHandler<GetMenuListCommand, APIResult<List<GetMeunList>>>
    {
        private readonly IBaseRepository<Menu> menuRep;
        private readonly IMapper mapper;

        public GetMenuListCommandHandler(IBaseRepository<Menu> menuRep, IMapper mapper)
        {
            this.menuRep = menuRep;
            this.mapper = mapper;
        }
        public Task<APIResult<List<GetMeunList>>> Handle(GetMenuListCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<GetMeunList>> result = new APIResult<List<GetMeunList>>();
            result.Code = APIEnum.成功;
            result.Msg = APIEnum.查询成功.ToString();
            result.data = GetTree(0);
            return Task.FromResult(result);
        }
        public List<GetMeunList> GetTree(long parentId)
        {
            var menus = menuRep.GetAll().Result.Where(x => x.PId == parentId);
            var menudto = mapper.Map<List<GetMeunList>>(menus);
            foreach (var item in menudto)
            {
                item.ChilDren = GetTree(item.MenuId);

            }
            return menudto;
        }
    }
}
